<template>
  <div class="mycategories-container">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-button class="addBtn" type="primary" @click="openAddCategories">添加分类</el-button>
      <!-- 添加分类对话框 -->
      <el-dialog title="添加分类" :visible.sync="addDialogVisible" width="40%" height="200px" :before-close="handleClose"
        @close="clearAddDialog">
        <el-form :model="addCategoriesForm" :rules="addCategoriesRules" ref="addCategoriesFormRef" label-width="100px">
          <el-form-item label="分类名称：" prop="cat_name">
            <el-input v-model="addCategoriesForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类：">
            <el-cascader clearable v-model="parentCategoriesArray" :options="parentCategoriesList"
              :props="categoriesProps" @change="handleChange">
            </el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCategories">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改分类对话框 -->
      <el-dialog title="修改分类" :visible.sync="editDialogVisible" width="40%" height="200px" :before-close="handleClose">
        <el-form :model="editCategoriesForm" :rules="editCategoriesRules" ref="editCategoriesFormRef"
          label-width="100px">
          <el-form-item label="分类名称：" prop="cat_name">
            <el-input v-model="editCategoriesForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCategories">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 表格 -->
      <tree-table index-text="#" show-index border :data="categoriesList" :columns="columns" :expand-type="false"
        :selection-type="false" :show-row-hover="false">
        <!-- 是否有效 -->
        <template slot="isOk" slot-scope="scope" width="100px">
          <i class="el-icon-success" v-if="!scope.row.effective" style="color: lightGreen"></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 等级 -->
        <template slot="level" slot-scope="scope" width="100px">
          <el-tag type="primary" effect="plain" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" effect="plain" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" effect="plain" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope" width="100px">
          <el-tooltip effect="dark" content="编辑" placement="top">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEditCategories(scope.row)">编辑
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="top">
            <el-button type="danger" icon="el-icon-edit" size="mini" @click="deleteCategories(scope.row.cat_id)">删除
            </el-button>
          </el-tooltip>
        </template>
      </tree-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="query.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="query.pagesize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>
<script>
  export default {
    name: 'MyCategories',
    data() {
      return {
        deleteId: 0,
        parentCategoriesArray: [],
        categoriesProps: {
          value: 'cat_id',
          label: 'cat_name',
          children: 'children',
          expandTrigger: 'hover',
          checkStrictly: true
        },
        parentCategoriesList: [],
        addCategoriesForm: {
          cat_pid: 0,
          cat_name: '',
          cat_level: 0
        },
        addCategoriesRules: {
          cat_name: [{
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          }]
        },
        addDialogVisible: false,
        editDialogVisible: false,
        editCategoriesForm: {
          cat_pid: 0,
          cat_name: '',
        },
        editCategoriesRules: {
          cat_name: [{
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          }]
        },
        categoriesList: [],
        total: 0,
        query: {
          type: 3,
          pagenum: 1,
          pagesize: 5
        },
        columns: [{
            label: "分类名称",
            prop: "cat_name"
          },
          {
            label: "是否有效",
            prop: "effective",
            type: 'template',
            template: 'isOk'
          },
          {
            label: "排序",
            prop: "cat_level",
            type: 'template',
            template: 'level'
          },
          {
            label: '操作',
            type: 'template',
            template: 'opt'
          }
        ]
      }
    },
    created() {
      this.initCategoriesList()
    },
    methods: {
      async initCategoriesList() {
        const {
          data: res
        } = await this.$http.get('categories', {
          params: this.query
        })
        if (res.meta.status !== 200) {
          this.$message({
            showClose: true,
            message: '获取商品分类失败',
            type: 'error'
          })
        } else {
          this.categoriesList = res.data.result
          this.total = res.data.total
        }
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.query.pagesize = val
        this.initCategoriesList()
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.query.pagenum = val
        this.initCategoriesList()
      },
      openAddCategories() {
        this.addDialogVisible = true
        this.getParentCategories()
      },
      //获取父级分类
      async getParentCategories() {
        const {
          data: res
        } = await this.$http.get('categories', {
          params: {
            type: 2
          }
        })
        if (res.meta.status !== 200) {
          this.$message({
            showClose: true,
            message: '获取商品分类失败',
            type: 'error'
          })
        } else {
          this.parentCategoriesList = res.data
        }
      },
      handleChange(value) {
        console.log(value)
        if (this.parentCategoriesArray.length > 0) {
          this.addCategoriesForm.cat_pid = this.parentCategoriesArray[this.parentCategoriesArray.length - 1]
          this.addCategoriesForm.cat_level = this.parentCategoriesArray.length
          return
        } else {
          this.addCategoriesForm.cat_pid = 0
          this.addCategoriesForm.cat_level = 0
        }
      },
      addCategories() {
        this.$refs.addCategoriesFormRef.validate(async valid => {
          if (!valid) return
          const {
            data: res
          } = await this.$http.post('categories', this.addCategoriesForm)
          if (res.meta.status !== 201) {
            this.$message({
              showClose: true,
              message: '添加商品分类失败',
              type: 'error'
            })
          } else {
            this.$message({
              showClose: true,
              message: '添加商品分类成功',
              type: 'success'
            })
            this.addDialogVisible = false
            this.initCategoriesList()
          }
        })
      },
      clearAddDialog() {
        this.$refs.addCategoriesFormRef.resetFields()
        this.parentCategoriesArray = []
        this.addCategoriesForm.cat_level = 0
        this.addCategoriesForm.cat_pid = 0
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      openEditCategories(categories) {
        this.editDialogVisible = true
        this.editCategoriesForm = categories
      },
      editCategories() {
        this.$refs.editCategoriesFormRef.validate(async valid => {
          if (!valid) return
          const {
            data: res
          } = await this.$http.put('categories/' + this.editCategoriesForm.cat_id, {
            cat_name: this.editCategoriesForm.cat_name
          })
          if (res.meta.status !== 200) {
            this.$message({
              showClose: true,
              message: '修改商品分类失败',
              type: 'error'
            })
          } else {
            this.$message({
              showClose: true,
              message: '修改商品分类成功',
              type: 'success'
            })
            this.editDialogVisible = false
            this.initCategoriesList()
          }
        })
      },
      deleteCategories(id) {
        this.deleteId = id
        this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {
            data: res
          } = await this.$http.delete('categories/' + this.deleteId)
          if (res.meta.status !== 200) {
            this.$message({
              showClose: true,
              message: '删除商品分类失败',
              type: 'error'
            })
          } else {
            this.$message({
              showClose: true,
              message: '删除商品分类成功',
              type: 'success'
            })
            this.initCategoriesList()
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    }
  }

</script>
<style lang="less" scoped>
  .box-card {
    margin-top: 15px;
    padding: 0;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1) !important;
  }

  .addBtn {
    margin-bottom: 15px;
  }

  .el-cascader {
    width: 100%;
  }

</style>
